package com.boco.ibssystem.common.exception.support;

import com.boco.ibssystem.common.RequestContextHolderUtil;
import com.boco.ibssystem.common.exception.IException;
import com.boco.ibssystem.common.result.AbstractResult;
import com.boco.ibssystem.common.result.support.FailtureResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 全局异常处理器
 *
 * @author Created by wangfan on 2018-02-22 上午 11:29.
 */
@ControllerAdvice
@Slf4j
public class MyExceptionHandler {

  @ResponseBody
  @ExceptionHandler
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  public AbstractResult errorHandler(Exception ex) {
    String uri = RequestContextHolderUtil.getRequest().getRequestURI();
    FailtureResult result;
    /** 根据不同错误获取错误信息 */
    if (ex instanceof IException) {
      result = FailtureResult.failture(((IException) ex).getCode(), uri, null, ex.getMessage());
    } else if (ex instanceof BindingResult) {
      /**
       * 添加处理数据校验的异常处理
       * @author sunshixong
       */
      StringBuilder message = new StringBuilder();
      BindingResult bindingResult = (BindingResult) ex;
      bindingResult.getAllErrors().forEach((ObjectError error) -> {
        message.append(error.getDefaultMessage());
        message.append(",");
      });
      result = FailtureResult.failture(HttpStatus.INTERNAL_SERVER_ERROR.value(), uri, null, message.toString());
    } else {
      result = FailtureResult.failture(HttpStatus.INTERNAL_SERVER_ERROR.value(), uri, null, ex.getMessage());
      log.debug("错误信息", ex);
    }
    return result;
  }

}
